package com.daxt.controller.filemanager;

import java.util.List;

import com.daxt.common.annotations.LoginAuth;
import com.daxt.common.annotations.LoginUser;
import com.daxt.mapper.accept.BusinessInfoMapper;
import com.daxt.mapper.accept.ColumnsMapper;
import com.daxt.mapper.accept.FormDataMapper;
import com.daxt.mapper.accept.MateralInfoMapper;
import com.daxt.mapper.archives.ArchivesDocFileMapper;
import com.daxt.model.dic.BehaveLogType;
import com.daxt.model.service.accept.vo.BusinessInfo;
import com.daxt.model.service.accept.vo.Columns;
import com.daxt.model.service.accept.vo.FormData;
import com.daxt.model.service.accept.vo.MateralInfo;
import com.daxt.model.service.archives.vo.ArchivesBehaveLog;
import com.daxt.model.service.archives.vo.ArchivesDocFile;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.service.ArchivesBehaveLogService;
import com.daxt.service.ArchivesService;
import com.daxt.service.OperationLogService;
import com.daxt.utils.ArchivesUtil;
import com.daxt.utils.BaseUtil;
import com.daxt.utils.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daxt.common.result.PageInfo;
import com.daxt.common.result.PageUtil;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.mapper.archives.ArchivesDocMapper;
import com.daxt.model.service.archives.result.ArchivesList;
import com.daxt.model.service.archives.vo.ArchivesDoc;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "回收站")
@RestController
@RequestMapping("/recycleBin")
public class RecycleBinController {

	@Autowired
	private ArchivesDocMapper archivesDocMapper;
	@Autowired
	private ArchivesDocFileMapper archivesDocFileMapper;
	@Autowired
	private ArchivesService archivesService;
	@Autowired
	private ColumnsMapper columnsMapper;
	@Autowired
	private MateralInfoMapper materalInfoMapper;
	@Autowired
	private BusinessInfoMapper businessInfoMapper;
	@Autowired
	private FormDataMapper formDataMapper;
	@Autowired
	private ArchivesBehaveLogService archivesBehaveLogService;
	@Autowired
	private OperationLogService operationLogService;

//	@Value(value = "${systemConfig.createNum}")
//	private Integer createNum;

	@ApiOperation(value = "获取列表  卷/件", notes = "")
	@GetMapping("/doc")
	public Result<PageInfo<ArchivesDoc>> list(
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			@ApiParam("") @RequestParam(value = "extType", required = false) String extType,
			@ApiParam("") @RequestParam(value = "fondsId", required = false) String fondsId,
			@ApiParam("") @RequestParam(value = "classNum", required = false) String classNum,
			@ApiParam("条件") @RequestParam(value = "condition", required = false) String condition,
			@ApiParam("doc dossier") @RequestParam(value = "fileType", required = false) String fileType,
			@ApiParam("关键词") @RequestParam(value = "keywords", required = false) String keywords,
			@ApiParam("0 整理  1归档审批  2 归档") @RequestParam(value = "state", required = false) String state) {
		Page<ArchivesDoc> page = new Page<ArchivesDoc>(pageNum == null ? 0 : pageNum, pageSize == null ? 10 : pageSize);
		QueryWrapper<ArchivesDoc> queryWrapper = new QueryWrapper<ArchivesDoc>();
		if (!StringUtils.isEmpty(fondsId))
			queryWrapper.eq("fondsId", fondsId);
		if (!StringUtils.isEmpty(classNum))
			queryWrapper.eq("classNum", classNum);
		if (!StringUtils.isEmpty(extType))
			queryWrapper.eq("typeNum", extType);
		if (!StringUtils.isEmpty(fileType))
			queryWrapper.eq("fileType", fileType);
		if (!StringUtils.isEmpty(keywords))
			queryWrapper.like("title", keywords);
		if (!StringUtils.isEmpty(state))
			queryWrapper.eq("state", state);
		queryWrapper.eq("isDelete", "1");
		IPage<ArchivesDoc> info = archivesDocMapper.selectPage(page, queryWrapper);
		PageInfo<ArchivesDoc> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(),
				info.getRecords());
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", data);
	}

	@ApiOperation(value = "删除  卷/件", notes = "")
	@DeleteMapping("/doc")
	@LoginAuth()
	public Result<ArchivesList> delete(@ApiIgnore @LoginUser UserInfo loginUser,@RequestBody List<String> ids,HttpServletRequest request) {
		String ip= IpUtil.getIP(request);
		try {
		if (ids != null && ids.size() > 0) {

			List<ArchivesDocFile> adfList = archivesDocFileMapper.selectList(new QueryWrapper<ArchivesDocFile>().in("docId",ids));
			//删除附件
			archivesService.deleteFile(adfList);

			archivesDocMapper.deleteBatchIds(ids);
			columnsMapper.delete(new QueryWrapper<Columns>().in("docId",ids));

			QueryWrapper<ArchivesDoc> wrapperDel = new QueryWrapper<ArchivesDoc>();
			wrapperDel.in("dossierId", ids);

			//删除子文件的附件
			List<ArchivesDoc> adocList = archivesDocMapper.selectList(wrapperDel);
			if(BaseUtil.listIsNotNullElement(adocList)){
				List<Long> dosIds= ArchivesUtil.buildDocIds(adocList);
				List<ArchivesDocFile> adf2List = archivesDocFileMapper.selectList(new QueryWrapper<ArchivesDocFile>().in("docId",ids));
				archivesService.deleteFile(adf2List);

				materalInfoMapper.delete(new QueryWrapper<MateralInfo>().in("docId",dosIds));
				businessInfoMapper.delete(new QueryWrapper<BusinessInfo>().in("docId",dosIds));
				formDataMapper.delete(new QueryWrapper<FormData>().in("docId",dosIds));
			}

			archivesDocMapper.delete(wrapperDel);

			operationLogService.saveLog("4", "回收站删除", loginUser,ip);

			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "删除成功", null);
		} else {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "删除至少选择一项！！！", null);
		}
		}catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "删除失败",null);
		}
	}

	@ApiOperation(value = "恢复  卷/件", notes = "")
	@PutMapping("/doc")
	@LoginAuth()
	public Result<ArchivesList> recovery(@ApiIgnore @LoginUser UserInfo loginUser,
										 @RequestBody List<String> ids,
										 HttpServletRequest request) {
		if (ids != null && ids.size() > 0) {
			try {
			for (String string : ids) {
				ArchivesDoc doc = archivesDocMapper.selectById(string);
				if (doc != null) {
					if ("dossier".equals(doc.getFileType())) {
						ArchivesDoc entity = new ArchivesDoc();
						entity.setId(Long.parseLong(string));
						entity.setIsDelete("0");
						archivesDocMapper.updateById(entity);

						ArchivesDoc entityDoc = new ArchivesDoc();
						entityDoc.setIsDelete("0");
						QueryWrapper<ArchivesDoc> updateWrapperDoc = new QueryWrapper<ArchivesDoc>();
						updateWrapperDoc.eq("dossierId", string);
						archivesDocMapper.update(entityDoc, updateWrapperDoc);
					} else if ("doc".equals(doc.getFileType())) {
						if (doc.getDossierId().intValue() > 1) {
							ArchivesDoc doc1 = archivesDocMapper.selectById(doc.getDossierId());
							if (doc1 == null) {
								return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(),
										"文件题名:" + doc.getTitle() + " 所属案卷不存在，请直接删除文件！！！", null);
							} else if ("1".equals(doc1.getIsDelete())) {
								return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "请先还原文件所属案卷！！！", null);
							}
						}
						ArchivesDoc entity = new ArchivesDoc();
						entity.setId(Long.parseLong(string));
						entity.setIsDelete("0");
						archivesDocMapper.updateById(entity);
					}
				}
			}
			}catch (Exception e) {
				e.printStackTrace();
				return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "恢复失败", null);
			}

			archivesBehaveLogService.saveArchivesBehaveLog(new ArchivesBehaveLog(BaseUtil.listToString(ids), BehaveLogType.RECOVER.getKey(), BehaveLogType.RECOVER.getValue(),"将档案移出回收站"),loginUser ,request);

			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "恢复成功", null);
		} else {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "恢复至少选择一项！！！", null);
		}
	}

}
